Shader "Custom/ToonEye"
{
    Properties
    {
        [Header(Base Settings)]
        _BaseMap("眼睛贴图", 2D) = "white" {}
        _BaseColor("基础颜色", Color) = (1,1,1,1)
        
        [Header(Highlights)]
        _MatCapTex("MatCap高光贴图", 2D) = "white" {}
        _MatCapIntensity("MatCap强度", Range(0, 4)) = 2.0 // 增大范围
        _MatCapColor("MatCap颜色", Color) = (1, 1, 1, 1)
        _MatCapContrast("MatCap对比度", Range(0.5, 3)) = 1.5 // 新参数
        
        [Header(Shading)]
        _ShadowColor("阴影颜色", Color) = (0.7, 0.7, 0.8, 1.0)
        _ShadowThreshold("阴影阈值", Range(0, 1)) = 0.5
        _ShadowSmooth("阴影平滑度", Range(0.001, 0.5)) = 0.05
        
        [Header(Rim Light)]
        [Toggle(_USE_RIM)] _UseRim("启用边缘光", Float) = 1
        _RimColor("边缘光颜色", Color) = (1, 1, 1, 1)
        _RimPower("边缘光强度", Range(1, 10)) = 3
        _RimThreshold("边缘光阈值", Range(0, 1)) = 0.2

        // --- Surface Options ---
        [Header(Surface Options)]
        [Enum(UnityEngine.Rendering.CullMode)] _Cull("Cull Mode", Float) = 2 // Back
        [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend("Src Blend", Float) = 1 // One
        [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend("Dst Blend", Float) = 0 // Zero
        [Enum(UnityEngine.Rendering.BlendOp)] _BlendOp("Blend Operation", Float) = 0 // Add
        [Toggle] _ZWrite("ZWrite", Float) = 1
        [Enum(UnityEngine.Rendering.CompareFunction)] _ZTest("ZTest", Float) = 4 // LEqual

        // --- Stencil Settings ---
        [Header(Stencil Settings)]
        _StencilRef("Stencil Ref", Float) = 0
        [Enum(UnityEngine.Rendering.CompareFunction)] _StencilComp("Stencil Comp", Float) = 8 // Always
        [Enum(UnityEngine.Rendering.StencilOp)] _StencilPass("Stencil Pass", Float) = 0 // Keep
        [Enum(UnityEngine.Rendering.StencilOp)] _StencilFail("Stencil Fail", Float) = 0 // Keep
        [Enum(UnityEngine.Rendering.StencilOp)] _StencilZFail("Stencil ZFail", Float) = 0 // Keep
        [IntRange] _StencilReadMask("Read Mask", Range(0, 255)) = 255
        [IntRange] _StencilWriteMask("Write Mask", Range(0, 255)) = 255

        // 添加新的Properties
        [Header(Eye Features)]
        _IrisRadius("虹膜半径", Range(0, 1)) = 0.5
        _IrisEdgeSoftness("虹膜边缘柔化", Range(0, 0.1)) = 0.05
        _EyeDepth("眼球深度", Range(0, 0.1)) = 0.05
        _PupilSize("瞳孔大小", Range(0, 1)) = 0.3
        _PupilResponsiveness("瞳孔响应度", Range(0, 1)) = 0.5
        _SpecularPower("高光强度", Range(1, 128)) = 32
        _SpecularIntensity("高光亮度", Range(0, 1)) = 0.5
        
        // 新增圈圈眼旋转功能
        [Header(Circle Eyes Rotation)]
        [Toggle(_USE_CIRCLE_ROTATION)] _UseCircleRotation("启用圈圈旋转", Float) = 0
        _RotationAngle("旋转角度", Range(0, 360)) = 0
        _RotationCenter("旋转中心", Vector) = (0.5, 0.5, 0, 0)
        _RotationSpeed("自动旋转速度", Range(-10, 10)) = 2
        _EffectBlend("效果混合权重", Range(0, 1)) = 1

        // 渲染设置
        [HideInInspector] _SrcBlend("__src", Float) = 1.0
        [HideInInspector] _DstBlend("__dst", Float) = 0.0
        [HideInInspector] _ZWrite("__zw", Float) = 1.0
        [HideInInspector] _Cull("__cull", Float) = 2.0
    }
    
    SubShader
    {
        Tags {"RenderType" = "Opaque" "RenderPipeline" = "UniversalPipeline" "Queue" = "Geometry"}
        LOD 300
        
        Pass
        {
            Name "ForwardLit"
            Tags {"LightMode" = "UniversalForward"}
            
            Blend [_SrcBlend][_DstBlend]
            ZWrite [_ZWrite]
            Cull [_Cull]
            
            // 添加模板测试设置
            Stencil
            {
                Ref [_StencilRef]
                Comp [_StencilComp]
                Pass [_StencilPass]
                Fail [_StencilFail]
                ZFail [_StencilZFail]
                ReadMask [_StencilReadMask]
                WriteMask [_StencilWriteMask]
            }
            
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma prefer_hlslcc gles
            #pragma exclude_renderers d3d11_9x
            
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS
            #pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE
            #pragma multi_compile _ _SHADOWS_SOFT
            #pragma multi_compile_fog
            
            #pragma shader_feature_local _USE_RIM
            #pragma shader_feature_local _USE_CIRCLE_ROTATION
            
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
            
            // 计算旋转UV的辅助函数
            float2 RotateUV(float2 uv, float angle, float2 pivot)
            {
                float cosAngle = cos(angle);
                float sinAngle = sin(angle);
                float2 offset = uv - pivot;
                float2 rotatedUV;
                rotatedUV.x = offset.x * cosAngle - offset.y * sinAngle + pivot.x;
                rotatedUV.y = offset.x * sinAngle + offset.y * cosAngle + pivot.y;
                return rotatedUV;
            }
            
            struct Attributes
            {
                float4 positionOS : POSITION;
                float3 normalOS : NORMAL;
                float2 texcoord : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };
            
            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float2 uv : TEXCOORD0;
                float3 positionWS : TEXCOORD1;
                float3 normalWS : TEXCOORD2;
                float3 viewDirWS : TEXCOORD3;
                float fogFactor : TEXCOORD4;
                float3 normalVS : TEXCOORD5;  // 视图空间法线，用于MatCap
                float3 positionVS : TEXCOORD7; // 视图空间位置，用于改进MatCap
                #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
                float4 shadowCoord : TEXCOORD6;
                #endif
                UNITY_VERTEX_INPUT_INSTANCE_ID
                UNITY_VERTEX_OUTPUT_STEREO
            };
            
            CBUFFER_START(UnityPerMaterial)
            float4 _BaseMap_ST;
            float4 _BaseColor;
            float _MatCapIntensity;
            float4 _MatCapColor;
            float _MatCapContrast;
            float4 _ShadowColor;
            float _ShadowThreshold;
            float _ShadowSmooth;
            float4 _RimColor;
            float _RimPower;
            float _RimThreshold;
            float _IrisRadius;
            float _IrisEdgeSoftness;
            float _EyeDepth;
            float _PupilSize;
            float _PupilResponsiveness;
            float _SpecularPower;
            float _SpecularIntensity;
            float _RotationAngle;
            float4 _RotationCenter;
            float _RotationSpeed;
            float _EffectBlend;
            CBUFFER_END
            
            TEXTURE2D(_BaseMap); SAMPLER(sampler_BaseMap);
            TEXTURE2D(_MatCapTex); SAMPLER(sampler_MatCapTex);
            
            Varyings vert(Attributes input)
            {
                Varyings output = (Varyings)0;
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_TRANSFER_INSTANCE_ID(input, output);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
                
                output.uv = TRANSFORM_TEX(input.texcoord, _BaseMap);
                
                VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
                VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS);
                
                output.positionCS = vertexInput.positionCS;
                output.positionWS = vertexInput.positionWS;
                output.normalWS = normalize(normalInput.normalWS);
                output.viewDirWS = GetWorldSpaceNormalizeViewDir(output.positionWS);
                output.fogFactor = ComputeFogFactor(vertexInput.positionCS.z);
                
                // 计算视图空间法线，用于MatCap UV计算
                output.normalVS = TransformWorldToViewDir(output.normalWS);
                output.positionVS = TransformWorldToView(output.positionWS);
                
                #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
                output.shadowCoord = GetShadowCoord(vertexInput);
                #endif
                
                return output;
            }
            
            half4 frag(Varyings input) : SV_Target
            {
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
                
                float2 uv = input.uv;
                
                // 应用圈圈旋转效果
                #if defined(_USE_CIRCLE_ROTATION)
                    // 计算动态旋转角度（自动旋转）
                    float dynamicAngle = _RotationAngle * (3.14159265359f / 180.0f); // 转换为弧度
                    dynamicAngle += _RotationSpeed * _Time.y; // 添加自动旋转，_Time是Unity内置时间变量
                    
                    // 应用旋转
                    uv = RotateUV(uv, dynamicAngle, _RotationCenter.xy);
                #endif
                
                // 眼球深度和凹陷效果
                float2 centeredUV = uv - float2(0.5, 0.5);
                float distFromCenter = length(centeredUV);
                float irisEdge = smoothstep(_IrisRadius - _IrisEdgeSoftness, _IrisRadius, distFromCenter);
                
                // 视差效果
                float2 offsetUV = uv - normalize(input.normalVS).xy * _EyeDepth * (1.0 - irisEdge);
                half4 eyeColor = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, offsetUV) * _BaseColor;
                
                // 基本光照计算
                #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
                Light mainLight = GetMainLight(input.shadowCoord);
                #else
                Light mainLight = GetMainLight();
                #endif
                
                float3 normalWS = normalize(input.normalWS);
                float3 viewDirWS = normalize(input.viewDirWS);
                float NdotL = dot(normalWS, mainLight.direction);
                float halfLambert = NdotL * 0.5 + 0.5;
                
                // 简单卡通阴影
                float shadow = smoothstep(_ShadowThreshold - _ShadowSmooth, _ShadowThreshold + _ShadowSmooth, halfLambert);
                half3 shadedColor = lerp(_ShadowColor.rgb * eyeColor.rgb, eyeColor.rgb, shadow);
                
                // 改进的MatCap高光计算
                float3 viewNormal = normalize(input.normalVS);
                float3 viewDir = float3(0, 0, 1); // 在视图空间中，视线方向是Z轴
                float3 r = reflect(-viewDir, viewNormal);
                float m = 2.0 * sqrt(r.x * r.x + r.y * r.y + (r.z + 1.0) * (r.z + 1.0));
                float2 matcapUV = r.xy / m + 0.5;
                
                // 增强对比度
                half3 matcapColor = SAMPLE_TEXTURE2D(_MatCapTex, sampler_MatCapTex, matcapUV).rgb;
                matcapColor = pow(matcapColor, _MatCapContrast); // 使用参数控制对比度
                half3 specularColor = matcapColor * _MatCapIntensity * _MatCapColor.rgb;
                
                // 在虹膜区域增强高光
                specularColor *= 1.0 + (1.0 - irisEdge) * 0.5;
                
                // 瞳孔动态效果
                float averageBrightness = dot(mainLight.color.rgb, float3(0.299, 0.587, 0.114));
                float dynamicPupilSize = lerp(_PupilSize, _PupilSize * 0.7, averageBrightness * _PupilResponsiveness);
                float pupilMask = 1.0 - smoothstep(dynamicPupilSize - 0.05, dynamicPupilSize, distFromCenter / _IrisRadius);
                eyeColor.rgb *= lerp(float3(1,1,1), float3(0.1, 0.1, 0.15), pupilMask * 0.8);
                
                // 计算边缘光
                half3 rimLight = 0;
                #if defined(_USE_RIM)
                    float NdotV = dot(normalWS, viewDirWS);
                    float rimFactor = pow(1.0 - saturate(NdotV), _RimPower);
                    rimFactor = smoothstep(_RimThreshold, _RimThreshold + 0.1, rimFactor);
                    rimLight = _RimColor.rgb * rimFactor;
                #endif
                
                // 添加水润高光
                float3 halfVector = normalize(mainLight.direction + viewDirWS);
                float NdotH = max(0, dot(normalWS, halfVector));
                float specular = pow(NdotH, _SpecularPower) * _SpecularIntensity;
                
                // 组合最终颜色
                half3 finalColor = shadedColor * mainLight.color;
                
                // 改进MatCap高光混合
                finalColor = lerp(finalColor, finalColor + specularColor, saturate(_MatCapIntensity * 0.5));
                
                finalColor += rimLight;      // 添加边缘光
                finalColor += specular * mainLight.color.rgb; // 添加水润高光
                finalColor *= mainLight.shadowAttenuation; // 应用阴影衰减
                
                // 应用环境光
                float3 ambient = SampleSH(normalWS);
                finalColor += ambient * eyeColor.rgb * 0.3;
                
                #if defined(_USE_CIRCLE_ROTATION)
                    // 应用效果混合权重
                    finalColor = lerp(eyeColor.rgb, finalColor, _EffectBlend);
                #endif
                
                // 应用雾效
                finalColor = MixFog(finalColor, input.fogFactor);
                
                return half4(finalColor, eyeColor.a);
            }
            ENDHLSL
        }
        
        // 阴影投射Pass
        Pass
        {
            Name "ShadowCaster"
            Tags {"LightMode" = "ShadowCaster"}
            
            ZWrite On
            ZTest LEqual
            ColorMask 0
            Cull[_Cull]
            
            // 添加模板测试设置
            Stencil
            {
                Ref [_StencilRef]
                Comp [_StencilComp]
                Pass [_StencilPass]
                Fail [_StencilFail]
                ZFail [_StencilZFail]
                ReadMask [_StencilReadMask]
                WriteMask [_StencilWriteMask]
            }
            
            HLSLPROGRAM
            #pragma vertex ShadowPassVertex
            #pragma fragment ShadowPassFragment
            
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
            
            float4 _BaseMap_ST;
            
            struct Attributes
            {
                float4 positionOS   : POSITION;
                float3 normalOS     : NORMAL;
                float2 texcoord     : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };
            
            struct Varyings
            {
                float2 uv           : TEXCOORD0;
                float4 positionCS   : SV_POSITION;
                UNITY_VERTEX_INPUT_INSTANCE_ID
                UNITY_VERTEX_OUTPUT_STEREO
            };
            
            float3 _LightDirection;
            
            float4 GetShadowPositionHClip(Attributes input)
            {
                float3 positionWS = TransformObjectToWorld(input.positionOS.xyz);
                float3 normalWS = TransformObjectToWorldNormal(input.normalOS);
                float3 lightDirection = _LightDirection;
                float4 positionCS = TransformWorldToHClip(ApplyShadowBias(positionWS, normalWS, lightDirection));
                
                #if UNITY_REVERSED_Z
                positionCS.z = min(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
                #else
                positionCS.z = max(positionCS.z, positionCS.w * UNITY_NEAR_CLIP_VALUE);
                #endif
                
                return positionCS;
            }
            
            Varyings ShadowPassVertex(Attributes input)
            {
                Varyings output;
                UNITY_SETUP_INSTANCE_ID(input);
                UNITY_TRANSFER_INSTANCE_ID(input, output);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
                
                output.uv = TRANSFORM_TEX(input.texcoord, _BaseMap);
                output.positionCS = GetShadowPositionHClip(input);
                return output;
            }
            
            half4 ShadowPassFragment(Varyings input) : SV_TARGET
            {
                UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
                return 0;
            }
            
            ENDHLSL
        }
    }
    
    FallBack "Universal Render Pipeline/Lit"
    CustomEditor "UnityEditor.ShaderGraph.PBRMasterGUI"
}